﻿using ServerSocket.common;
using ServerSocket.entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ServerSocket.server
{
    class Client
    {

        private Socket clientSocket;
        private Server server;
        Message msg = new Message();

        /// <summary>
        /// 当前用户的房间
        /// </summary>
        public Room Room { get; set; }

        /// <summary>
        /// 用户信息
        /// </summary>
        public User User { get; set; }

        public Client() { }

        public Client(Socket clientSocket, Server server)
        {
            this.clientSocket = clientSocket;
            this.server = server;
        }

        public void Open()
        {
            clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.LastIndex, SocketFlags.None, ReceiveCallbackAsync, null);
        }

        private void ReceiveCallbackAsync(IAsyncResult ar)
        {
            try
            {
                int count = clientSocket.EndReceive(ar);
                if (count == 0)
                {
                    Console.WriteLine("已有客户端退出[0]");
                    Close();
                }
                msg.ReadMessage(count, OnProcessMessage);
                Open();
            }
            catch (Exception e)
            {
                Console.WriteLine("已有客户端退出[Exception]");
                Close();
            }
        }

        /// <summary>
        /// 解析数据完成回调
        /// </summary>
        /// <param name="data"></param>
        private void OnProcessMessage(string data)
        {
            //Console.WriteLine("客户端发送的数据："+data);
            //处理请求
            server.HandleRequest(data, this);
        }

        /// <summary>
        /// 关闭链接
        /// </summary>
        private void Close()
        {
            if (clientSocket != null)
            {
                clientSocket.Close();
            }
            server.RemoveClient(this);
        }

        /// <summary>
        /// 向客户端发送数据
        /// </summary>
        /// <param name="data"></param>
        public void SendData(string data)
        {
            byte[] dataBytes = Message.PackData(data);
            clientSocket.Send(dataBytes);
        }

        /// <summary>
        /// 向客户端发送数据(序列化)
        /// </summary>
        /// <param name="data"></param>
        public void SendData<T>(T data)
        {
            byte[] dataBytes = Message.PackData(data);
            clientSocket.Send(dataBytes);
        }

    }
}
